#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
const char *ssid     = "MiHome";
const char *password = "ftwc1982";

WiFiUDP ntpUDP;

// You can specify the time server pool and the offset (in seconds, can be
// changed later with setTimeOffset() ). Additionally you can specify the
// update interval (in milliseconds, can be changed using setUpdateInterval() ).
//NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
NTPClient timeClient(ntpUDP, "ntp.aliyun.com", 8 * 3600, 60000);
struct dateTime
{
    int year;
    u_char month;
    u_char date;
    u_char day;
    u_char hour;
    u_char minute;
    u_char second;
};

dateTime timeSync()
{
    dateTime dt;
    unsigned long epochTime;
    timeClient.update();
    epochTime = timeClient.getEpochTime();
    dt.year = year(epochTime);
    dt.month = month(epochTime);
    dt.date = day(epochTime);
    dt.day = weekday(epochTime);
    dt.hour = hour(epochTime);
    dt.minute = minute(epochTime);
    dt.second = second(epochTime);
    return dt;
}
void setup(){
  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  timeClient.begin();
}

void loop() {dateTime dt;
dt=timeSync();

  Serial.printf("%d-%d-%d %d %d:%d:%d\n",dt.year,dt.month,dt.date,dt.day,dt.hour,dt.minute,dt.second);

  delay(1000);
}
